/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.main;

import com.seari.bean.cctv.AgreInfo;
import com.seari.bean.cctv.Login;
import com.seari.bean.pa.PaResponse;
import com.seari.cctv.handler.CctvClient1;
import com.seari.main.bean.WinccoaMessageBean;
import com.seari.main.utils.CommandHelper;
import com.seari.pa.PaClient;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import jdk.nashorn.internal.parser.TokenType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Rainbow
 */
public class CommandHandler extends ChannelInboundHandlerAdapter
{
    private int keyvalue;
    private String step;
    CctvClient1 cctvClient;
    PaClient paClient;
    protected static Logger logger = LoggerFactory.getLogger(CctvClient1.class);
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
    {
//        ByteBuf byteBuf = (ByteBuf)msg;
//        byte[] bytes = new byte[]{};
//        byteBuf.readBytes(bytes);
//        String str = new String(bytes, Charset.forName("utf-8"));
        String message  = msg.toString();
        String[] split = message.split("\\|");
        if(split.length != CommandHelper.WINCCOA_MESSAGE_LENGTH)
        {
            return;
        }
        WinccoaMessageBean winccoaMessageBean = new WinccoaMessageBean(split);
        System.out.println(winccoaMessageBean);
        switch (split[0]) {
            case "CCTV":
                if(-1!=split[1].indexOf("/")){
                    String commandString = split[1];
                    String[] commandSplit = commandString.split("\\/");
                    cctvClient = new CctvClient1(commandSplit[0], Integer.parseInt(commandSplit[1]));
                    cctvClient.setup();
                }
                else if (-1!=split[1].indexOf("*")) {
                    String commandString = split[1];
                    String[] commandSplit = commandString.split("\\*");
                    Login login = 
                            new Login(Integer.parseInt(commandSplit[0]), commandSplit[1], commandSplit[2], commandSplit[3], Integer.parseInt(commandSplit[4]));
                    cctvClient.sendXml(login);
                } else{
                    String commandString = split[1];
                    String[] commandSplit = commandString.split("\\+");
                    // System.out.println(winccoaMessageBean);
                    //keyvalue = Integer.parseInt(winccoaMessageBean.getCommand());
                    //step = winccoaMessageBean.getDetail();
                    this.clickFunction(Integer.parseInt(commandSplit[0]), Integer.parseInt(commandSplit[1]),Integer.parseInt(commandSplit[2]), commandSplit[3]);
                }
                break;
            case "PA":
                if(-1!=split[1].indexOf("/")){
                    String commandString = split[1];
                    String[] commandSplit = commandString.split("\\/");
                    paClient = new PaClient(commandSplit[0], Integer.parseInt(commandSplit[1]));
                    paClient.setup();
                }else if (-1!=split[1].indexOf("*")) {
                    String commandString = split[1];
                    String[] commandSplit = commandString.split("\\*");
                    PaResponse paResponse = new PaResponse();

                    String staNum =commandSplit[0];// this.stationNum.getText();
                    paResponse.stationNum = Integer.valueOf(staNum);

                    String d0 = commandSplit[1];//this.d0.getText();
                    String d1 = commandSplit[2];//this.d1.getText();
                    String d2 = commandSplit[3];//this.d2.getText();
                    String d3 = commandSplit[4];// this.d3.getText();
                    String paNumStr = d3 + d2 + d1 + d0;
                    paResponse.paNum = Integer.valueOf(paNumStr,2).byteValue();
                    paResponse.chk = (byte) (0x31+paResponse.stationNum + paResponse.paNum);
                    paClient.responseList.add(paResponse);   
                }else if (-1!=split[1].indexOf("+")) {
                    paClient.sendNoAnswerFrame();
                }else if (-1!=split[1].indexOf("-")) {
                    paClient.sendNoAnswerFrame();
                }

                break;
            default:
                return;
        }
        
 
    }
    private void clickFunction(int infotype,int keyvalue, int state, String step){
        AgreInfo ai = new AgreInfo(infotype, keyvalue, state, step);
        cctvClient.sendXml(ai);
        try
        {
            TimeUnit.MILLISECONDS.sleep(10);
        } catch (Exception e)
        {
           logger.warn(e.getMessage());
        }
        ai.setState(0);
        cctvClient.sendXml(ai);
    }
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
    {
        super.exceptionCaught(ctx, cause); //To change body of generated methods, choose Tools | Templates.
       // System.out.println("unhandled exception caught");
    }
    
    
    
    
}
